

rm(list = ls())


# Purpose: 
#  Build prior data for phi from CHES data. 
#
#
# 
#



#############
# LOAD DATA #
#############


# LOAD CHES data 
######
#1999-2014_CHES_dataset_means.csv
#1999-2006_ChapelHillSurvey.csv

ches <- read.csv("./datasource/1999-2014_CHES_dataset_means.csv")

#EC: include only eastern european countries
ches <- ches[ches$eastwest!='west',]
ches <- ches[,c("party_id","lrgen", "family", "year")]
colnames(ches) <- c("chesid", "lrpos", "partyfam", "year")



# LOAD ParlGov data
######
parlgov <- read.csv('./datasource/pargov_party.csv')
convert <- parlgov[,c("cmp", "chess")]
convert <- convert[!is.na(convert$ches), ]
convert <- convert[duplicated(convert)==FALSE,]
colnames(convert) <- c("cmp", "ches")



##################################
# CALCULATE PARTY FAMILY POSTION #
##################################

# MERGE
######

ches <- merge(convert, ches, by.x="ches", by.y="chesid", all.x=F, all.y=T)
ches$lrpos <- scale(ches$lrpos, scale=F)	
chesdata <- ches

ches$year <- NULL

# CALCULATE mean/variance for party families 
######

listfam <- sort(unique(ches$partyfam))[1:7]
namefam <- c("right", "conservativ", "liberal", "christ.-demo.", 
				"socialist", "left", "green", "regionalist", "non", "confessional", "agrarian")[1:7]

nfam <- length(listfam)
mu0 <- matrix(NA, nfam+1, 1)
sigmainv0 <- matrix(NA, nfam+1, 1)

for(i in 1:nfam){
	x <- ches[ches$partyfam==listfam[i],]
	mu0[i] <- mean(x$lrpos)
	sigmainv0[i] <- 1/var(x$lrpos)
	}

colnames(mu0) <- c("lrmu0")
rownames(mu0) <- c(listfam, 12)

mu0[nfam+1] <- 0
sigmainv0[nfam+1] <- 0.09


####################################
# ASSIGN PARTY FAMILY ID TO CMP ID #
####################################

# Select 
ches <- ches[,c("cmp", "partyfam")]
ches <- ches[duplicated(ches)==FALSE,]

# Assign party family '12' to all CMP parties 
# without unique family assignment in the CHESS data.
filtcmp <- dimnames(table(ches$cmp))[[1]][table(ches$cmp)==2]
ches[ches$cmp %in% filtcmp, "partyfam" ] <- (nfam+1)
ches$partyfam[ches$partyfam > nfam] <- (nfam+1)



# SAVE #
########

chesprior <- list(ches=ches, mu0=mu0, sigmainv0=sigmainv0, nfam=nfam, chesdata=chesdata)
save(chesprior, file="chesprior_east.Rdata")